package cRedis

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"

	"gitee.com/csingo/cLog"
)

func Client(ctx *gin.Context, name ...string) *redis.Client {
	var connection string
	if len(name) == 0 {
		connection = DefaultClient
	} else {
		connection = name[0]
	}

	client := container.Get(connection).(*redis.Client)
	if client == nil {
		cLog.SetCallerSkip(2)
		defer cLog.SetCallerSkip(1)
		cLog.WithContext(ctx, map[string]any{
			"source":     "cRedis.Client",
			"connection": name,
		}).Panic("redis connection is not exists")
	}
	client = client.WithContext(ctx)

	return client
}

func AddConnection(ctx *gin.Context, name string, config *RedisConf_Client) error {
	var err error
	connector := NewGoRedisConnector(name, config)
	err = connector.Connect()
	if err != nil {
		cLog.SetCallerSkip(2)
		defer cLog.SetCallerSkip(1)
		cLog.WithContext(ctx, map[string]any{
			"source": "cRedis.AddConnection",
			"name":   name,
			"config": config,
			"err":    err.Error(),
		}).Error("redis连接异常")
		return err
	}
	if container.Is(connector) {
		container.Save(connector)
	}
	return err
}
